#include "languagerecognizer.h"
#include "requestcontenthelper.h"

#include <QDebug>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkReply>

LanguageRecognizer::LanguageRecognizer(QObject* parent)
    : QNetworkAccessManager(parent)
{
    connect(this, &LanguageRecognizer::finished, this, &LanguageRecognizer::onReply);
}

void LanguageRecognizer::recognize(const QString& text)
{
    m_content.textToRecognize = text;
    m_content.salt = RequestContentHelper::generateSalt();
    m_content.sign = RequestContentHelper::generateSign(stringToSignFromContent(m_content));

    QMap<QString, QString> paramsWithKey;
    paramsWithKey.insert(KEY_TEXT, m_content.textToRecognize);
    paramsWithKey.insert(KEY_APPID, m_content.appid);
    paramsWithKey.insert(KEY_SALT, m_content.salt);
    paramsWithKey.insert(KEY_SIGN, m_content.sign);

    QString url = RequestContentHelper::generateRequestContent(m_content.address, paramsWithKey);
    QNetworkRequest request;
    request.setUrl(QUrl(url));
    get(request);
}

void LanguageRecognizer::onReply(QNetworkReply* reply)
{
    emit languageRecgnized(m_content.textToRecognize, languageInReply(reply));
}

Language LanguageRecognizer::languageInReply(QNetworkReply* reply)
{
    if (!reply || reply->error() != QNetworkReply::NoError)
        return Language::Unknow;

    QString result = reply->readAll();
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(result.toUtf8(), &error);
    if (error.error != QJsonParseError::NoError || doc.isNull())
        return Language::Unknow;

    QJsonObject object = doc.object();
    QJsonObject dataObject = object.value(KEY_DATA).toObject();
    QString language = dataObject.value(KEY_SRC).toString();

    return RequestContentHelper::languageStringToType(language);
}

QString LanguageRecognizer::stringToSignFromContent(const LanguageRecognizer::RequestContent& content)
{
    auto stringToSign = content.appid + content.textToRecognize + content.salt + content.pwd;
    return stringToSign;
}
